package leetcode.tree;

import java.util.ArrayList;
import java.util.List;

//113. 路径总和 II
public class Lc113 {
    List<List<Integer>> ans = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if (root == null) return ans;
        getPathSum(root, 0, targetSum, new ArrayList<>());
        return ans;
    }

    private void getPathSum(TreeNode node, int sum, int targetSum, List<Integer> list) {
        list.add(node.val);
        sum += node.val;
        if (node.left == null && node.right == null) {
            if (sum == targetSum)
                ans.add(new ArrayList<>(list));
        }
        if (node.left != null) getPathSum(node.left, sum, targetSum, list);
        if (node.right != null) getPathSum(node.right, sum, targetSum, list);
        sum -= node.val;
        list.remove(list.size() - 1);
    }
}
